package com.moon.icoresso.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName StringRedisTemplate
 * @Description 限制key只能为String
 * @Author menbbo
 * @Date 2021/2/12 15:56
 * @Version V1.0
 **/
@Component
public class StringRedisService<String,V> {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 设置过期时间
     * @param key
     * @param timeout
     * @param timeUnit
     * @return
     */
    public Boolean expire(String key, long timeout, TimeUnit timeUnit){
        return redisTemplate.expire(key,timeout,timeUnit);
    }

    /**
     * 删除
     * @param key
     * @return
     */
    public Boolean delete(String key){
        return redisTemplate.delete(key);
    }

    /**
     * 添加值
     * @param key
     * @param value
     */
    public void set(String key,V value){
        redisTemplate.opsForValue().set(key,value);
    }

    /**
     * 向reids中保存值并设置过期时间，时间单位默认为秒
     * @param key
     * @param value
     * @param timeout
     */
    public void set(String key,V value,long timeout){
        redisTemplate.opsForValue().set(key,value,timeout,TimeUnit.SECONDS);
    }

    /**
     * 向redis中保存值，过期时间单位自行设置
     * @param key
     * @param value
     * @param timeout
     * @param timeUnit
     */
    public void set(String key,V value,long timeout,TimeUnit timeUnit){
        redisTemplate.opsForValue().set(key,value,timeout,timeUnit);
    }

    /**
     * 根据key值获得value
     * @param key
     * @return
     */
    public V get(String key){
      ValueOperations <String,V>valueOperations = redisTemplate.opsForValue();
      return valueOperations.get(key) ;
    }
}


















